package com.example.first.thread;

import java.util.concurrent.TimeUnit;

/**
 * @Author LSQ
 * @Description TODO
 * @date 2021/8/29 9:37
 * @Version 1.0
 */

public class LearnVolatile {

    public volatile static int age = 100;

    public static void setAge() {
        age = age + 1;
    }

    public static int getAge() {
        return age;
    }

    public static void main(String[] args) {
        Runnable runnable1 = () -> {
            String threadName = Thread.currentThread().getName();
            setAge();
            System.out.println(threadName + " set age " + getAge());
        };

        Runnable runnable2 = () -> {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName + " print age == " + age);

            // 这里为什么进不去？
            while (age == 100) {
                try {
                    TimeUnit.MILLISECONDS.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(threadName + " running...");

            }

        };

        // 这样加volatile依然没用， Task1设置了101，Task2依然可能读到是100
        Thread thread2 = new Thread(runnable2, "Task2");
        // thread2.setName("Task2");
        thread2.start();

        Thread thread1 = new Thread(runnable1);
        thread1.setName("Task1");
        thread1.start();


    }


}
